<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Data;
use App\Models\Member;
use App\Models\Notice;
use App\Models\Question;
use App\Models\QuestionMember;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class NoticeController extends BaseController {

    /**
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
//        print_r($params);die;
        $build = Notice::query();
        if (isset($params['status'])){
            $build->where('status', $params['status']);
        }

        $pageSize = $request->input('pageSize', 50);

        $data = $build->paginate($pageSize);
        return $this->success($data);
    }


    public function create(Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        if (!isset($params['notice_title']) && empty($params['notice_title'])){
            return $this->errorCode('10001', [], '请填写标题');
        }
        if (!isset($params['content']) && empty($params['content'])){
            return $this->errorCode('10001', [], '请填写内容');
        }
        $result = Notice::query()->firstOrCreate(['notice_title' => $params['notice_title'], 'content' => $params['content']]);

        return $this->success($result, '添加成功');

    }

    public function destroy($id, Request $request)
    {
        $question = Notice::query()->where('notice_id', $id)->first();

        if (!$question){
            return $this->errorCode('10001', [], '公告不存在');
        }

        try {
            $result = $question->delete();
        } catch (\Exception $e) {
            return $this->errorCode('10001', [], '删除失败');
        }
        return $this->success($result, '删除成功');

    }


    public function update($id, Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Notice::query()->where('notice_id', $id)->first();
        if (!$data){
            return $this->errorCode('10001', [], '公告不存在');
        }

        if (!isset($params['notice_title']) && empty($params['notice_title'])){
            return $this->errorCode('10001', [], '请填写标题');
        }
        if (!isset($params['content']) && empty($params['content'])){
            return $this->errorCode('10001', [], '请填写内容');
        }
        $result = Notice::query()->where('notice_id', $id)->update([
            'notice_title' => $params['notice_title'],
            'content' => $params['content']
        ]);
        return $this->success($result, '修改成功');
    }

}